package io.github.lee.app.unsplash.ui.main.search

import android.app.Application
import com.chad.library.adapter.base.BaseQuickAdapter
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.app.unsplash.repository.PhotoRepository
import io.github.lee.app.unsplash.repository.domain.Photo
import io.github.lee.app.unsplash.repository.params.OrderBy
import io.github.lee.app.unsplash.ui.main.home.page.TopicPhotoAdapter
import io.github.lee.core.vm.BaseRefreshViewModel
import javax.inject.Inject

@HiltViewModel
class MainSearchVM @Inject constructor(
    application: Application,
    private val repo: PhotoRepository
) : BaseRefreshViewModel<Photo>(application) {


    override fun onCreateAdapter(): BaseQuickAdapter<Photo, *> =
        TopicPhotoAdapter()

    //===Desc:======================================================================================

    override fun onRefreshOrLoadMore(isRefresh: Boolean) {
        super.onRefreshOrLoadMore(isRefresh)
        if (isRefresh) {
            currentPage = 1
        } else {
            currentPage++
        }

        launchResult({
            repo.photos(currentPage, orderBy = OrderBy.Popular)
        }, {
            error()
            if (!isRefresh) currentPage--
        }) {
            if (!it.isSuccess()) {
                error()
                if (!isRefresh) currentPage--
                return@launchResult
            }
            val data = it.data
            if (data.isNullOrEmpty()) {
                empty()
                if (!isRefresh) currentPage--
                return@launchResult
            }
            if (isRefresh) {
                submitList(data)
                refreshSuccess()
            } else {
                addAll(data)
                loadMoreSuccess(true)
            }
        }
    }
}